package com.xywy.wjk.paser;

import java.util.HashMap;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.util.Log;

import com.google.gson.Gson;
import com.xywy.R;
import com.xywy.common.net.AsyncHttpClient;
import com.xywy.common.net.OnResultListenerAdapter;
import com.xywy.common.net.Parser;
import com.xywy.common.util.MD5Util;
import com.xywy.me.bean.UserKeeper;
import com.xywy.wjk.bean.WeightData;

public class WeightDataParser {

	protected static final String TAG = "WeightDataParser";
	private Context mContext;
	private Handler mHandler;
	private WeightData data;
	private String userid;
	private String secret_key = "213aBc$l;@13";

	public WeightDataParser(Context context, Handler handler, WeightData data) {
		this.mContext = context;
		this.mHandler = handler;
		this.data = data;
		SharedPreferences sp = context.getSharedPreferences("config",
				Context.MODE_PRIVATE);
//		userid = sp.getString("userid", "");
		userid = UserKeeper.getCurrentUser(context).getUserid();

	}

	// 封装Parser参数
	private Parser paramsParser;
	// 异步加载
	private AsyncHttpClient asyncHttpClient;

	private HashMap<String, Object> params;

	// 处理网络请求
	public void sendMsg(String action) throws Exception {
		paramsParser = new Parser();
		// 请求路径
		paramsParser.action = mContext.getString(R.string.upload_weight_data);
		// 请求方式
		paramsParser.request = "post";
		// 参数
		params = new HashMap<String, Object>();
		params.put("app_username", "xywy_tizhong");
		params.put("xywy_userid", userid);
		params.put("sort", "tizhong");
		// -------------------
		Gson gson = new Gson();
		String dataStr = gson.toJson(data);
		params.put("data", dataStr);
		System.out.println(dataStr);
		// -------------------
		String sn = secret_key + userid + "tizhong" + dataStr + "xywy_tizhong";
		params.put("sn", MD5Util.md5(sn));
		paramsParser.map = params;
		// 传递上下文
		paramsParser.context = this.mContext;

		asyncHttpClient = AsyncHttpClient.getInstance();
		asyncHttpClient.exeute(paramsParser, onResultListenerAdapter);
	}

	OnResultListenerAdapter onResultListenerAdapter = new OnResultListenerAdapter() {
		@Override
		public <T extends Parser> void onSuccess(T resultParser, int resultCode) {
			super.onSuccess(resultParser, resultCode);
			Log.d(TAG, "本次数据上传成功");

		}

		@Override
		public <T extends Parser> void onFailure(T parserResult, int resultCode) {
			Log.d(TAG, "本次数据上传失败");
		};

		public <T extends Parser> void onNoNetWork(T paramParser, int resultCode) {
			Log.d(TAG, "暂无网络");
		};

	};
}
